package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NewsDao;
import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.service.NewsService;
import com.cn.wanxi.util.IOTool;

import java.io.File;

public class NewsServiceImpl implements NewsService {
    private static final String FILE_NAME = "newsForHomePage.txt";

    @Override
    public NewsModel[] getNewsModelsForHomePage() {
//        1.创建文件
//        创建文件的前提：必须由路径，文件夹，文件名
        File file = IOTool.createFile(FILE_NAME);
//        2.写入数据
        String[] data = NewsDao.data;
        IOTool.saveData(file, data);
//        3.读取数据
        String result = IOTool.readData(file);
//        4.封装数据
        return setData(result);
    }

    private NewsModel[] setData(String result) {
        String[] results = result.split("\n");

        String[] titles = results[0].split(", ");
        String[] contents = results[1].split(", ");
        int length=titles.length;
        NewsModel[] newsModels = new NewsModel[length];
        for (int i = 0; i < length; i++) {
            NewsModel model = new NewsModel();
            model.setTitle(titles[i]);
            model.setContent(contents[i]);
            newsModels[i] = model;
        }
        return newsModels;
    }
}
